﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Interop;
using System.Data;
using System.Windows.Threading;

using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Imaging;
using System.IO;

using com.google.zxing;
using com.google.zxing.qrcode;
using com.google.zxing.qrcode.encoder;
using com.google.zxing.common;
using System.Drawing;
using com.google.zxing.qrcode.detector;
using System.Diagnostics;
using nLearning.QR;

namespace nLearning.UC
{
    /// <summary>
    /// Interaction logic for Login.xaml
    /// </summary>
    public partial class Login : UserControl
    {
        public Login()
        {
            
            InitializeComponent();
            camControl = new CamControl();
            process = new QRProcess();
            process.ResultFound += new EventHandler<ProcessArgs>(process_ResultFound);
            process.Start();
        }

        void process_ResultFound(object sender, ProcessArgs e)
        {
            txtUser.Dispatcher.Invoke(new Action(delegate()
            {
                txtUser.EditValue = e.Result;
                if (camControl.SelectedDevice.IsRunning)
                {
                    camControl.SelectedDevice.SignalToStop();
                }
                RoutedEventArgs miss = null;
                btLog_Click(sender, miss);
            }));
            process.Stop();
            //set login
        }

        //Reference the GDI DeleteObject method.
        [System.Runtime.InteropServices.DllImport("GDI32.dll")]
        public static extern bool DeleteObject(IntPtr objectHandle);

        //VideoCaptureDevice cam;
        FilterInfoCollection dvList;
        QRProcess process;
        CamControl camControl;

        private void ucLogin_Loaded(object sender, RoutedEventArgs e)
        {
            dvList = new FilterInfoCollection(FilterCategory.VideoInputDevice);
        }

        private void btLog_Click(object sender, RoutedEventArgs e)
        {
            string value ="";
               txtUser.Dispatcher.Invoke(new Action(delegate()
               {
                   value = txtUser.Text.Trim();
                   txtUser.Clear();
               }));
            if (value != Warehouse.EXIT_CODE)
            {
                #region do something
                //--login here
                if (LearningLib.Login(value))
                {
                    //end login and open course--
                    UC.Course course = new Course();
                    WpfPageTransitions.PageTransition transition = new WpfPageTransitions.PageTransition();
                    transition.TransitionType = WpfPageTransitions.PageTransitionType.Slide;
                    transition.ShowPage(course);
                    Window.GetWindow(this).Content = transition;

                    if (camControl.SelectedDevice.IsRunning)
                    {
                        camControl.SelectedDevice.SignalToStop();
                    }
                }
                else
                {
                    Message.Info(cString.ID("login.fail"));
                }
                #endregion
            }
            else if (value == Warehouse.EXIT_CODE)
            {
                if (camControl.SelectedDevice.IsRunning)
                {
                    camControl.SelectedDevice.SignalToStop();
                }
                //Window.GetWindow(this).Close();
                Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
                Application.Current.Shutdown();
            }
        }

        private void txtUser_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                RoutedEventArgs miss = null;
                btLog_Click(sender, miss);
            }
        }

        private void QRImage_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            if (dvList.Count > 0)
            {
                process = new QRProcess();
                process.ResultFound += new EventHandler<ProcessArgs>(process_ResultFound);
                process.Start();

                if (camControl.SelectedDevice.IsRunning)
                {
                    camControl.SelectedDevice.SignalToStop();
                }

                camControl.SetCamera(0);
                camControl.SelectedDevice.NewFrame += new NewFrameEventHandler(SelectedDevice_NewFrame);

                camControl.SelectedDevice.Start();
            }
            else
            {
                cMessage msg = new cMessage(cString.ID("error.no_device"), cMessage.BUTTON_TYPE.OK);
                msg.ShowDialog();
            }
        }

        void SelectedDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            using (UnmanagedImage uimage = UnmanagedImage.FromManagedImage(eventArgs.Frame))
            {
                try
                {
                    using (Bitmap image = uimage.ToManagedImage())
                    {
                        IntPtr hBitMap = image.GetHbitmap();
                        try
                        {
                            BitmapSource bmaps = Imaging.CreateBitmapSourceFromHBitmap(hBitMap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                            bmaps.Freeze();
                            Dispatcher.Invoke((Action)(() =>
                            {
                                imgUser.Source = bmaps;
                            }), DispatcherPriority.Render, null);

                            process.NewBitmap(image);
                        }
                        finally
                        {
                            DeleteObject(hBitMap);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }
            //throw new NotImplementedException();
        }

        private void ucLogin_Unloaded(object sender, RoutedEventArgs e)
        {
            if (camControl.SelectedDevice.IsRunning)
            {
                camControl.SelectedDevice.SignalToStop();
            }
            process.Stop();
        }

        private void txtUser_EditValueChanged(object sender, DevExpress.Xpf.Editors.EditValueChangedEventArgs e)
        {
            try
            {
                string eVal = txtUser.EditValue.ToString();
                btDel.Visibility = System.Windows.Visibility.Visible;
            }
            catch
            {
            }
        }

        private void btDel_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            UC.Login relog = new Login();
            WpfPageTransitions.PageTransition transition = new WpfPageTransitions.PageTransition();
            transition.TransitionType = WpfPageTransitions.PageTransitionType.Slide;
            transition.ShowPage(relog);
            Window.GetWindow(this).Content = transition;
        }
    }
}
